//
//  LCircleView.swift
//  AnimationDemo
//
//  Created by 李明明 on 16/2/29.
//  Copyright © 2016年 李明明. All rights reserved.
//

import UIKit

class LCircleView: UIView {

    var duration: CFTimeInterval = 0.2
    var length: Float = 0
    var bezier: UIBezierPath! = UIBezierPath()
    var shapeLayer: CAShapeLayer! = CAShapeLayer()
    var startH: CGFloat = 0
    var end: CGFloat = 0
    override init(frame: CGRect) {
        super.init(frame: frame)
        end = bounds.height
        start()
        layer.addSublayer(shapeLayer)
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    func makeBezier()-> UIBezierPath {
        let position = CGPointMake(bounds.width / 2, 0)
        bezier.addArcWithCenter(position, radius: 5, startAngle: 0, endAngle: CGFloat(M_PI * 2), clockwise: true)
        shapeLayer.path = bezier.CGPath
        return bezier
    }
    func start() {
        animationStart(startH, endHeight: end)
    }
    func animationStart(startHeight: CGFloat, endHeight: CGFloat) {
        let animation = CABasicAnimation(keyPath: "position")
        animation.fromValue = NSValue.init(CGPoint: CGPointMake(0, startHeight))
        animation.toValue = NSValue.init(CGPoint: CGPointMake(0, endHeight))
        animation.duration = duration
        animation.beginTime = 0
        let animation1 = CABasicAnimation(keyPath: "position")
        animation1.fromValue = NSValue.init(CGPoint: CGPointMake(0, endHeight))
        animation1.toValue = NSValue.init(CGPoint: CGPointMake(0, startHeight))
        animation1.duration = duration
        animation1.beginTime = duration
        makeBezier()
        let group = CAAnimationGroup()
        group.duration = duration * 2
        group.repeatCount = HUGE
        group.animations = [animation, animation1]
        shapeLayer.addAnimation(group, forKey: "circle")
        shapeLayer.fillColor = UIColor.redColor().CGColor
    }
}
